package com.sojson.util;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.sojson.constant.Constant;

/**
 * Cookie工具类
 * 
 * @author liu
 * @date 2020-11-02
 */
public final class CookieUtil {

    /**
     * 获取Cookie的值, 不编码
     * 
     * @param request
     * @param cookieName
     *            cookie名称
     * @return 得到的cookie值
     * @throws UnsupportedEncodingException
     */
    public static String getCookieValue(HttpServletRequest request, String cookieName)
        throws UnsupportedEncodingException {
        return getCookieValue(request, cookieName, false);
    }

    /**
     * 获取Cookie的值, 以UTF-8解码
     * 
     * @param request
     * @param cookieName
     *            cookie名称
     * @return 得到的cookie值
     * @throws UnsupportedEncodingException
     */
    public static String getCookieValue(HttpServletRequest request, String cookieName, boolean isDecoder)
        throws UnsupportedEncodingException {
        Cookie[] cookieList = request.getCookies();
        if (StringUtil.isBlankObjectListOne(cookieList, cookieName)) {
            return null;
        }
        String retValue = null;
        for (int i = 0; i < cookieList.length; i++) {
            if (cookieList[i].getName().equals(cookieName)) {
                if (isDecoder) {
                    retValue = URLDecoder.decode(cookieList[i].getValue(), Constant.DEFAULT_ENCODING);
                } else {
                    retValue = cookieList[i].getValue();
                }
                break;
            }
        }
        return retValue;
    }

    /**
     * 获取Cookie的值, 以指定规则解码
     * 
     * @param request
     * @param cookieName
     *            cookie名称
     * @param encodeString
     *            解码规则
     * @return 得到的cookie值
     * @throws UnsupportedEncodingException
     */
    public static String getCookieValue(HttpServletRequest request, String cookieName, String encodeString)
        throws UnsupportedEncodingException {
        Cookie[] cookieList = request.getCookies();
        if (StringUtil.isBlankObjectListOne(cookieList, cookieName)) {
            return null;
        }
        String retValue = null;
        for (int i = 0; i < cookieList.length; i++) {
            if (cookieList[i].getName().equals(cookieName)) {
                retValue = URLDecoder.decode(cookieList[i].getValue(), encodeString);
                break;
            }
        }
        return retValue;
    }

    /**
     * 设置Cookie的值, 不设置生效时间默认浏览器关闭即失效, 不编码
     * 
     * @param request
     * @param response
     * @param cookieName
     *            cookie名称
     * @param cookieValue
     *            cookie值
     * @throws IOException 
     */
    public static void setCookie(HttpServletRequest request, HttpServletResponse response, String cookieName,
        String cookieValue) throws IOException {
        setCookie(request, response, cookieName, cookieValue, -1);
    }

    /**
     * 设置Cookie的值, 在指定时间内生效, 不编码
     * 
     * @param request
     * @param response
     * @param cookieName
     *            cookie名称
     * @param cookieValue
     *            cookie值
     * @param cookieMaxage
     *            生效时间:以秒为单位
     * @throws IOException 
     */
    public static void setCookie(HttpServletRequest request, HttpServletResponse response, String cookieName,
        String cookieValue, int cookieMaxage) throws IOException {
        setCookie(request, response, cookieName, cookieValue, cookieMaxage, false);
    }

    /**
     * 设置Cookie的值, 不设置生效时间默认浏览器关闭即失效, 是否编码
     * 
     * @param request
     * @param response
     * @param cookieName
     *            cookie名称
     * @param cookieValue
     *            cookie值
     * @param isEncode
     *            是否编码，以UTF-8编码
     * @throws IOException 
     */
    public static void setCookie(HttpServletRequest request, HttpServletResponse response, String cookieName,
        String cookieValue, boolean isEncode) throws IOException {
        setCookie(request, response, cookieName, cookieValue, -1, isEncode);
    }

    /**
     * 设置Cookie的值, 在指定时间内生效, 是否编码
     * 
     * @param request
     * @param response
     * @param cookieName
     *            cookie名称
     * @param cookieValue
     *            cookie值
     * @param cookieMaxage
     *            生效时间:以秒为单位
     * @param isEncode
     *            是否编码，以UTF-8编码
     * @throws IOException 
     */
    public static void setCookie(HttpServletRequest request, HttpServletResponse response, String cookieName,
        String cookieValue, int cookieMaxage, boolean isEncode) throws IOException {
        doSetCookie(request, response, cookieName, cookieValue, cookieMaxage, isEncode);
    }

    /**
     * 设置Cookie的值, 在指定时间内生效, 指定编码
     * 
     * @param request
     * @param response
     * @param cookieName
     *            cookie名称
     * @param cookieValue
     *            cookie值
     * @param cookieMaxage
     *            生效时间:以秒为单位
     * @param encodeString
     *            编码规则
     * @throws IOException 
     */
    public static void setCookie(HttpServletRequest request, HttpServletResponse response, String cookieName,
        String cookieValue, int cookieMaxage, String encodeString) throws IOException {
        doSetCookie(request, response, cookieName, cookieValue, cookieMaxage, encodeString);
    }

    /**
     * 删除Cookie带cookie域名
     * 
     * @param request
     * @param response
     * @param cookieName
     *            cookie名称
     * @throws IOException 
     */
    public static void deleteCookie(HttpServletRequest request, HttpServletResponse response, String cookieName)
        throws IOException {
        doSetCookie(request, response, cookieName, "", -1, false);
    }

    /**
     * 设置Cookie的值, 在指定时间内生效, 是否编码
     * 
     * @param request
     * @param response
     * @param cookieName
     *            cookie名称
     * @param cookieValue
     *            cookie值
     * @param cookieMaxage
     *            生效时间:以秒为单位
     * @param isEncode
     *            是否编码，以UTF-8编码
     * @throws IOException 
     */
    private static void doSetCookie(HttpServletRequest request, HttpServletResponse response, String cookieName,
        String cookieValue, int cookieMaxage, boolean isEncode) throws IOException {
        if (StringUtil.isBlank(cookieValue)) {
            cookieValue = "";
        } else if (isEncode) {
            // 给字符串设置编码
            cookieValue = StringUtil.encode(cookieValue);
        }
        Cookie cookie = new Cookie(cookieName, cookieValue);
        if (cookieMaxage > 0) {
            cookie.setMaxAge(cookieMaxage);
        }
        if (null != request) {// 设置域名的cookie
            String domainName = getDomainName(request);
            if (!"localhost".equals(domainName)) {
                cookie.setDomain(domainName);
            }
        }
        cookie.setPath("/");
        response.addCookie(cookie);
    }

    /**
     * 设置Cookie的值, 在指定时间内生效, 指定编码
     * 
     * @param request
     * @param response
     * @param cookieName
     *            cookie名称
     * @param cookieValue
     *            cookie值
     * @param cookieMaxage
     *            生效时间:以秒为单位
     * @param encodeString
     *            编码规则
     * @throws IOException 
     */
    private static void doSetCookie(HttpServletRequest request, HttpServletResponse response, String cookieName,
        String cookieValue, int cookieMaxage, String encodeString) throws IOException {
        if (StringUtil.isBlank(cookieValue)) {
            cookieValue = "";
        } else {
            // 给字符串设置编码
            cookieValue = StringUtil.encode(cookieValue, encodeString);
        }
        Cookie cookie = new Cookie(cookieName, cookieValue);
        if (cookieMaxage > 0) {
            cookie.setMaxAge(cookieMaxage);
        }
        if (null != request) {// 设置域名的cookie
            String domainName = getDomainName(request);
            if (!"localhost".equals(domainName)) {
                cookie.setDomain(domainName);
            }
        }
        cookie.setPath("/");
        response.addCookie(cookie);
    }

    /**
     * 获取cookie的域名
     */
    private static String getDomainName(HttpServletRequest request) {
        String domainName = null;
        // http://www.baidu.com:8080/jqueryLearn/resources/request.jsp
        String serverName = request.getRequestURL().toString();
        if (StringUtil.isBlank(serverName)) {
            domainName = "";
        } else {
            serverName = serverName.toLowerCase();
            // www.baidu.com:8080/jqueryLearn/resources/request.jsp
            serverName = serverName.substring(7);
            final int end = serverName.indexOf("/");
            // www.baidu.com:8080
            serverName = serverName.substring(0, end);
            // [www,baidu,com:8080]
            final String[] domains = serverName.split("\\.");
            int len = domains.length;
            if (len > 3) {
                // www.xxx.com.cn
                domainName = "." + domains[len - 3] + "." + domains[len - 2] + "." + domains[len - 1];
            } else if (len <= 3 && len > 1) {
                // xxx.com or xxx.cn
                // .baidu.com:8080
                domainName = "." + domains[len - 2] + "." + domains[len - 1];
            } else {
                domainName = serverName;
            }
        }
        if (domainName != null && domainName.indexOf(":") > 0) {
            // [.baidu.com,8080]
            String[] ary = domainName.split("\\:");
            // .baidu.com
            domainName = ary[0];
        }
        // .baidu.com
        return domainName;
    }

}
